﻿using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SmartPlant.Services
{
    public class ItemListService : DynamicColumnService, IItemListService
    {

        public async Task<List<ItemList>> GetItemListBomAsync(string proId, GroupMode groupMode)
        {
            string url = $"/api/Project/{proId}/Item-List-Api/bom/{(byte)groupMode}";
            var result = await PostAsync<List<ItemList>>(url);
            return result.data;
        }

        public async Task<List<ViewQueryItemAttr>> GetDataColumnsAsync(string proId, GroupMode groupMode)
        {
            string uri = $"/api/Project/{proId}/Item-List-Api/bom-dafault-columns/{(byte)groupMode}";
            var res = await GetAsync<List<ViewQueryItemAttr>>(uri);
            return res.data;
        }

        public async Task<List<DynamicPropertyInfo>> InitPropertyInfosAsync(string proId, GroupMode groupMode)
        {
            string cacheKey = $"{proId}_ItemPropertyInfos_{groupMode}";
            List<DynamicPropertyInfo> propertyInfos;
            var cacheObj = GlobalObject.PropertyList.TryGetValue(cacheKey, out propertyInfos);
            if (cacheObj) return propertyInfos;
            var viewQueryItems = await GetDataColumnsAsync(proId, groupMode);
            propertyInfos = ConvertColumns(viewQueryItems);
            GlobalObject.PropertyList.Add(cacheKey, propertyInfos);
            return propertyInfos;
        }

        public async Task<List<DynamicPropertyInfo>> InitHookUpItemPropertyInfosAsync(string proId)
        {
            var cache = GlobalObject.HookUpItemPropertyInfos;
            if (cache == null)
            {
                string uri = $"/api/Project/{proId}/Item-List-Api/hookup-item-list-dafault-columns";
                var res = await GetAsync<List<ViewQueryItemAttr>>(uri);
                var viewQueryItems = res.data;
                var propertyInfos = ConvertColumns(viewQueryItems);
                cache = propertyInfos;
                GlobalObject.HookUpItemPropertyInfos = cache;
            }
            return cache;
        }

        public async Task<List<DynamicPropertyInfo>> InitHookUpComponentPropertyInfosAsync(string proId)
        {
            var cache = GlobalObject.HookUpComponentPropertyInfos;
            if (cache == null)
            {
                string uri = $"/api/Project/{proId}/Hook-Up-Component-api/hook-up-component-dafault-columns";
                var res = await GetAsync<List<ViewQueryItemAttr>>(uri);
                var viewQueryItems = res.data;
                var propertyInfos = ConvertColumns(viewQueryItems);
                cache = propertyInfos;
                GlobalObject.HookUpComponentPropertyInfos = cache;
            }
            return cache;
        }
    }
}
